/*
 * Copyright (C) 2013
 * Shopping
 */
package com.mshopping.app.ui;

import org.json.JSONObject;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.mshopping.app.R;
import com.mshopping.app.configs.Configs;
import com.mshopping.app.configs.UrlConfig;
import com.mshopping.app.entity.User;
import com.mshopping.app.http.AsyncHttpClient;
import com.mshopping.app.http.JsonHttpResponseHandler;
import com.mshopping.app.manager.GlobleManager;
import com.mshopping.app.ui.base.BaseActivity;
import com.mshopping.app.util.CommonLog;
import com.mshopping.app.util.LogFactory;

/*
 *This class is used for ...

 *  @autho liuhuan
 * @versio 1.0, 2013-9-1 下午5:30:43
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

	private static final String KEY_RES = "res";
	private static final String KEY_USER = "user";

	private Button btn_login = null;
	private EditText txt_username = null;
	private EditText txt_password = null;
	

	private AsyncHttpClient asyncHttpClient = null;

	private CommonLog log = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		initOther();
		findView();
		initView();
	}

	private void initOther() {
		asyncHttpClient = new AsyncHttpClient();
		log = LogFactory.createLog();
	}

	private void findView() {
		btn_login = (Button) findViewById(R.id.btn_login);
		txt_password = (EditText) findViewById(R.id.txt_password);
		txt_username = (EditText) findViewById(R.id.txt_username);
	}

	private void initView() {
		btn_login.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			String username = txt_username.getText().toString().trim();
			String password = txt_password.getText().toString().trim();

			String url = UrlConfig.LOGIN + "?passport=" + username + "&password=" + password;
			asyncHttpClient.get(url, httpResponseHandler);

			break;

		default:
			break;
		}
	}

	JsonHttpResponseHandler httpResponseHandler = new JsonHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, org.apache.http.Header[] headers, JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			log.d(response);

			try {

				boolean res = response.getBoolean(KEY_RES);
				if (res) {
					User user = new User();
					user.unpack(response.getJSONObject(KEY_USER));
					GlobleManager.getInstance().put(Configs.KEY_USER, user);

					openActivity(MainActivity.class);
					finish();
				} else {
					log.d("登陆失败");
				}

			} catch (Exception e) {
				log.e(e);
			}

		};

		@Override
		public void onFailure(Throwable error, String content) {
			super.onFailure(error, content);
		}
	};
}
